<?php
class data_kaixin001 extends data_social {
	private $akey;
	private $skey;
	private $authorize_url;

	public function __construct() {
		if (defined('KAIXIN001_APP_ID') and defined('KAIXIN001_AKEY') and defined('KAIXIN001_SKEY')) {
			$this->akey			= KAIXIN001_AKEY;
			$this->skey			= KAIXIN001_SKEY;
			$this->authorize_url	= KAIXIN001_AUTHORIZE_URL;
			
			parent::__construct();
		}
	}
	public function authorize_url ($flag = 'iframe/setting') {
		if ($this->akey) {
			$params = array (
				'client_id'		=> $this->akey,
				'redirect_uri'	=> data_social::make_callback_url(),
				'response_type'	=> 'code',
				'state'		=> data_social::make_state('kaixin001', $flag),
				'scope'		=> 'basic create_records',
				'display'		=> NULL,
			);
			return $this->authorize_url . "?" . http_build_query ( $params );
		} else return false;
	}
	public function code_2_token($code) {
		if ($this->akey and $code) {
			$kx_auth = new KxApiBase($this->akey, $this->skey);
			$api_param = array (
				'code'		=> $code,
				'redirect_uri'	=> data_social::make_callback_url(),
			);
			$api_result = $kx_auth->getAccessToken('code', $api_param);				// 用code换token ("access_token", "expires_in", "refresh_token", "scope")
			if (!isset($api_result['error_code']) and $api_result['access_token']) {									// 授权成功
				// 获取开心001用户的name和uid
				$kx_user = $this->get_me_info($api_result['access_token']);	// 返回(id, name)
				if ($kx_user) {
					// 重新整理token字段
					return array (
						'uid'			=> $kx_user['uid'],
						'access_token'	=> $api_result['access_token'],
						'refresh_token'	=> $api_result['refresh_token'],
						'ctime'		=> time(),
						'expires_in'		=> $api_result['expires_in'],
						'nick'			=> $kx_user['name'],
						'name'		=> $kx_user['name'],
					);
				} else {
					// 在get user info中已经记录了错误
					return false;
				}
			} else {
				new data_error_devel('新浪微博code to token错误', array('code'=>$code, 'api_result'=>$api_result), __CLASS__, __FUNCTION__, __LINE__);
				return false;
			}
		} return false;
	}
	public function token_valid_or_refresh_into_db ($token_from_db) {
		if (isset($token_from_db['uid']) and isset($token_from_db['access_token']) and isset($token_from_db['refresh_token'])) {
			// 检查token是否有效
			if ($this->is_token_valid($token_from_db['access_token'])) {	// 这里是用me info来判断是否有效，返回值中不包括与token相关的信息
				return $token_from_db;
			} else {
				// 刷新token
				$kx_auth = new KxApiBase($this->akey, $this->skey);
				$api_param = array (
					'refresh_token'	=> $token_from_db['refresh_token'],
				);
				$api_result = $kx_auth->getAccessToken('token', $api_param);				// 刷新token ("access_token", "expires_in", "refresh_token", "scope")
				if (!isset($api_result['error_code']) and $api_result ['access_token']) {
					$token_to_db = array (
						'uid'			=> $token_from_db['uid'],
						'access_token'	=> $api_result['access_token'],
						'refresh_token'	=> $api_result['refresh_token'],
						'ctime'		=> time(),
						'expires_in'		=> $api_result['expires_in'],
					);
					$this->save_token('kaixin001', $token_to_db);			// 写入数据库
					return $token_to_db;
				} else {
					$token_to_db = array (
						'uid'		=> $token_from_db['uid'],
						'ctime'	=> time()
					);
					$this->save_token('kaixin001', $token_to_db);			// 写入数据库
					new data_error_devel ( '开心001refresh token失败', array ('token_from_db' => $token_from_db, 'api_result' => $api_result), __CLASS__, __FUNCTION__, __LINE__ );
					return false;
				}
			}
		} else return false;
	}
	/**
	 * 获取自己的信息，用这个来验证token是否过期
	 * 
	 * @param type $access_token
	 * @return boolean
	 */
	private function is_token_valid ($access_token) {
//		return false;
		if ($this->get_me_info($access_token)) return true;
		else return false;
	}
	/**
	 * 从数据库中读出access token，然后去微博api验证有效性
	 *		如果超时了，没法更新，只能返回false
	 * 
	 * @param Int $uid
	 * @return Array = array (access_token, refresh_token, uid, ctime)
	 */
	public function get_token ($uid) {
		$data_user = new data_user();
		$user = $data_user->one($uid);
		return $this->token_valid_or_refresh_into_db($user['kaixin001_token']);
	}
	/**
	 * 
	 * @param type $token
	 * @return array (
	 *		array(uid, name),
	 *		array(uid, name),
	 *		...
	 *	)
	 */
	public function get_friends ($uid, $token='') {
		$uid = intval($uid);
		
		if ($uid) {
			if ($token) {
				$kx_client = new KxApiClient($this->akey, $this->skey, $token['access_token']);
				$limit = 50;			// 一次最多获取50条记录
				$api_result = $kx_client->friends_me('uid,name', 0, $limit);		// 字段中间不能有空格
				if ($api_result and !isset($api_result['error_code']) and $api_result['total']>0) {
					$return = $api_result['users'];
					for ($i=1; $i<ceil($api_result['total']/$limit); $i++) {
						$api_result = $kx_client->friends_me('uid,name', $i*$limit, $limit);		// 字段中间不能有空格
						if ($api_result and !isset($api_result['error_code']) and $api_result['users']) {
							$return = array_merge($return, $api_result['users']);
						}
					}
					if (is_array($return)) {
						foreach ($return as $k=>$v) {
							$return[$k] = array ('kaixin001_id'=>$v['uid'], 'name'=>$v['name']);
						}
					}
					$this->cache_write ( $uid, 'kaixin001', 'friends', $return );
					return $return ;
				} else {
					new data_error_devel('开心001读取好友时出错，或者这人一个好友也没有？', array('uid'=>$uid, 'token'=>$token, 'api_result'=>$api_result), __CLASS__, __FUNCTION__, __LINE__);
					return false;
				}
			} else {
				$cache = $this->cache_read ( $uid, 'kaixin001', 'friends' );
				if ($cache) {
					return $cache;
				} else {
					return false;
				}
			}
		} else return false;
	}
	public function get_me_info ($access_token) {
		if ($this->akey and $access_token) {
			$kx_client = new KxApiClient($this->akey, $this->skey, $access_token);
			$api_result = $kx_client->users_me('uid,name');			// 注意字段中间不能有空格！！！！！！
			if ($api_result['uid'] and !isset($api_result['error_code'])) {
				return $api_result;
			} else {
				new data_error_devel('开心001获取me info错误', array('access_token'=>$access_token, 'api_result'=>$api_result), __CLASS__, __FUNCTION__, __LINE__);
				return false;
			}
		} else return false;
	}
	public function post ($access_token, $content, $link, $at) {
		if ($access_token and $content and $link and $at) {
			if (mb_strlen($content) <= 140) {
				$kx_client = new KxApiClient($this->akey, $this->skey, $access_token);
				$api_param = array (
					'content' => $content . $link . $at
				);
				$api_result = $kx_client->records_add($api_param);		// array (rid)
				if (!isset($api_result['error_code']) and $api_result['rid']) {
					return $api_result;
				} else {
					new data_error_devel('开心001发布recorder时出错', array('access_token'=>$access_token, 'content'=>$content, 'link'=>$link, 'at'=>$at, 'api_result'=>$api_result), __CLASS__, __FUNCTION__, __LINE__);
					return false;
				}
			} else {
				new data_error_devel('开心001发布recorder时content超过140字符', array('access_token'=>$access_token, 'content'=>$content, 'link'=>$link, 'at'=>$at), __CLASS__, __FUNCTION__, __LINE__);
				return false;
			}

		} else return false;
	}
}
?>
